package cn.itcast.hotel;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.util.List;
/**
 * @Auth: zhuan
 * @Desc: 第二步：批量导入数据到索引库，一定要指定ID--保证幂等性
 * @Date: 2023/8/30 10:13
 */
@SpringBootTest(classes = HotelDemoApplication.class)
@RunWith(SpringRunner.class)
public class BatchDataImport {

    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Autowired
    HotelMapper hotelMapper;

    @Test
    public void importDataToIndex() throws IOException {
        BulkRequest bulkRequest = new BulkRequest("hotel");
        //1.查询数据库，获取符合条件的宾馆数据
        LambdaQueryWrapper<Hotel> queryWrapper = new LambdaQueryWrapper<>();
        List<Hotel> hotels = hotelMapper.selectList(queryWrapper);
        if(hotels == null || hotels.size() ==0){
            return;
        }
        for (Hotel hotel : hotels) {
            HotelDoc hotelDoc = new HotelDoc(hotel);
            Long id = hotelDoc.getId();
            //2.构建新增文档请求对象
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.source(JSON.toJSONString(hotelDoc), XContentType.JSON).id(String.valueOf(id));
            //3.把“新增文档请求对象”封装到“批量请求对象”中
            bulkRequest.add(indexRequest);
        }
        //4.执行批量导入请求
        BulkResponse response = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        //5.检测批量导入结果
    }
}
